let mediaStreamTrack = null;
function tip1(){
    $("#flag").html("正在打开摄像头")
}
function tip2(){
    $("#flag").html("请正视摄像头")
}
function tip3(){
    window.location.href="/";
}
let video = document.getElementById('video');
function openMedia() {
    setTimeout("tip1()","1000");
    setTimeout("tip2()","2000");
    setTimeout("takePhoto()","3000");
    $("#faceBox").show();
    let constraints = {
        video: { width: 400, height: 400 },
        audio: false
    };
    //获得video摄像头
    let promise = navigator.mediaDevices.getUserMedia(constraints);
    promise.then((mediaStream) => {
        mediaStreamTrack = mediaStream;
        video.srcObject = mediaStream;
        video.play();
    });
}
function closeMedia(){
    const tracks = mediaStreamTrack.getTracks();
    tracks.forEach(function(track) {
        track.stop();
    });
}

// 拍照
function takePhoto() {
    //获得Canvas对象
    let video = document.getElementById('video');
    let canvas = document.getElementById('canvas');
    let ctx = canvas.getContext('2d');
    ctx.drawImage(video, 0, 0, 400, 400);
    // toDataURL  ---  可传入'image/png'---默认, 'image/jpeg'
    let img = document.getElementById('canvas').toDataURL();
    // 这里的img就是得到的图片
    document.getElementById('imgTag').src=img;
    $("#flag").html("正在录入人脸信息");
    $.ajax({
        url: "/addFace",
        dataType:"json",   // 返回格式为json
        async: true,
        data: {
            imgBase64: img
        } , //参数值
        type: "POST", //请求方式
        success: function (data) {
            console.log(data)
            if(data.status == 200){
                closeMedia();
                $('#FaceLoginModal').modal("hide");
                $('#addFaceResult').modal();
            }else if(data.status == 500){
                $("#flag").html("检测不到人脸信息，请重新录入！")
                setTimeout("takePhoto()","3000");
            }
        }
    })
}

function toAdmin(){
    $("#faceBox").hide();
    $(location).attr('href', '/admin')
}
